# Copyright (c) 2024, lanlian and contributors
# For license information, please see license.txt

import json

import frappe
from frappe import _, msgprint
from frappe.model.mapper import get_mapped_doc
from frappe.utils import cint, cstr, flt
from frappe.model.document import Document


class EMSFaultRepairTask(Document):
	
	def before_insert(self):
		# 校验是否已经存在派工单
		if frappe.db.exists({"doctype": self.doctype, "ems_fault_report": self.ems_fault_report, "docstatus": ["in", (0,1)] }):
			frappe.throw(_("EMS Fault Repair Task Is Created. The BillNo is:{0}").format(frappe.db.exists({"doctype": self.doctype, "ems_fault_report": self.ems_fault_report, "docstatus": ["in", (0,1)] })))
		# 是否与B路线冲突校验: 如果故障报修单已经被有效外部维修单关联了, 就提示冲突
		if frappe.db.exists({"doctype": "EMS External Maintenance", "ems_fault_report": self.ems_fault_report, "docstatus": ["in", (0,1)] }):
			frappe.throw(("该源单'故障报修单'已经下推了'外部维修单': {0}, 不允许再下推'故障派工单'. 建议取消'外部维修单'或新增'故障报修单' ").format(frappe.db.exists({"doctype": "EMS External Maintenance", "ems_fault_report": self.ems_fault_report, "docstatus": ["in", (0,1)] })))

	# 故障派工保存时更新故障报修之状态
	def after_insert(self):
		frappe.get_doc("EMS Fault Report", self.ems_fault_report).set_repair_status()

	# 故障派工删除时更新故障报修之状态
	def after_delete(self):
		frappe.get_doc("EMS Fault Report", self.ems_fault_report).set_repair_status()

	# 故障派工取消时更新故障报修之状态
	def on_cancel(self):
		frappe.get_doc("EMS Fault Report", self.ems_fault_report).set_repair_status()

# 故障报修派工下推故障维修
@frappe.whitelist()
def make_fault_repair(source_name, target_doc=None, args=None):
	doc = get_mapped_doc(
		"EMS Fault Repair Task",
		source_name,
		{
			"EMS Fault Repair Task": {
				"doctype": "EMS Fault Repair",
				"field_map": {},
				"validation": {"docstatus": ["=", 1],},
			},
		},
		target_doc,
		ignore_permissions=True,
	)

	return doc